package src;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class SalesmanInfoPanel extends JDialog {
    private Connection connection;
    private JTable salesmanTable;
    private JTextField idField, nameField, phoneField;
    private JButton addButton, updateButton, deleteButton, searchButton;
    private JPanel inputPanel;

    public SalesmanInfoPanel(Connection connection) {
        super((JFrame) null, "业务员信息管理", true);
        this.connection = connection;
        setSize(800, 600);
        setLocationRelativeTo(null);
        getContentPane().setBackground(StyleConstants.BACKGROUND_COLOR);

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBackground(StyleConstants.BACKGROUND_COLOR);
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建标题面板
        JPanel titlePanel = new JPanel();
        titlePanel.setBackground(StyleConstants.THEME_COLOR);
        JLabel titleLabel = new JLabel("业务员信息管理", JLabel.CENTER);
        titleLabel.setFont(StyleConstants.TITLE_FONT);
        titleLabel.setForeground(Color.WHITE);
        titlePanel.add(titleLabel);
        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = {"ID", "姓名", "电话"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        salesmanTable = new JTable(model);
        salesmanTable.setFont(StyleConstants.TABLE_FONT);
        salesmanTable.getTableHeader().setFont(StyleConstants.TABLE_FONT);
        salesmanTable.setRowHeight(25);
        salesmanTable.setGridColor(StyleConstants.THEME_COLOR);
        JScrollPane scrollPane = new JScrollPane(salesmanTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建输入面板
        JPanel inputPanel = new JPanel(new GridLayout(4, 2, 10, 10));
        inputPanel.setBackground(StyleConstants.BACKGROUND_COLOR);
        inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));

        addInputField(inputPanel, "ID:", idField = new JTextField());
        addInputField(inputPanel, "姓名:", nameField = new JTextField());
        addInputField(inputPanel, "电话:", phoneField = new JTextField());

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setBackground(StyleConstants.BACKGROUND_COLOR);

        addButton = createStyledButton("添加");
        updateButton = createStyledButton("更新");
        deleteButton = createStyledButton("删除");
        searchButton = createStyledButton("查找");

        buttonPanel.add(addButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(searchButton);

        // 将输入面板和按钮面板添加到主面板
        JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
        bottomPanel.setBackground(StyleConstants.BACKGROUND_COLOR);
        bottomPanel.add(inputPanel, BorderLayout.CENTER);
        bottomPanel.add(buttonPanel, BorderLayout.SOUTH);
        mainPanel.add(bottomPanel, BorderLayout.SOUTH);

        add(mainPanel);
        refreshTable();

        // 添加表格选择监听器
        salesmanTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                int selectedRow = salesmanTable.getSelectedRow();
                if (selectedRow != -1) {
                    idField.setText(salesmanTable.getValueAt(selectedRow, 0).toString());
                    nameField.setText(salesmanTable.getValueAt(selectedRow, 1).toString());
                    phoneField.setText(salesmanTable.getValueAt(selectedRow, 2).toString());
                }
            }
        });

        // 添加按钮事件监听器
        addButton.addActionListener(e -> {
            SalesmanAddDialog dialog = new SalesmanAddDialog(this, connection);
            dialog.setVisible(true);
            refreshTable();
        });
        updateButton.addActionListener(e -> updateSalesman());
        deleteButton.addActionListener(e -> deleteSalesman());
        searchButton.addActionListener(e -> searchSalesman());
    }

    private void addInputField(JPanel panel, String labelText, JTextField textField) {
        JLabel label = new JLabel(labelText);
        label.setFont(StyleConstants.LABEL_FONT);
        panel.add(label);
        textField.setFont(StyleConstants.LABEL_FONT);
        panel.add(textField);
    }

    private JButton createStyledButton(String text) {
        JButton button = new JButton(text);
        button.setFont(StyleConstants.BUTTON_FONT);
        button.setBackground(StyleConstants.BUTTON_COLOR);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 添加鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(StyleConstants.BUTTON_COLOR.darker());
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(StyleConstants.BUTTON_COLOR);
            }
        });

        return button;
    }

    private void refreshTable() {
        DefaultTableModel model = (DefaultTableModel) salesmanTable.getModel();
        model.setRowCount(0);
        
        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM salesman")) {
            while (rs.next()) {
                model.addRow(new Object[]{
                    rs.getString("salesman_id"),
                    rs.getString("name"),
                    rs.getString("phone")
                });
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载业务员数据失败: " + e.getMessage());
        }
    }

    private void updateSalesman() {
        try {
            String sql = "UPDATE salesman SET name=?, phone=? WHERE salesman_id=?";
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, nameField.getText());
            pstmt.setString(2, phoneField.getText());
            pstmt.setString(3, idField.getText());
            
            pstmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "业务员信息更新成功！");
            clearFields();
            refreshTable();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "更新业务员信息失败: " + e.getMessage());
        }
    }

    private void deleteSalesman() {
        try {
            String sql = "DELETE FROM salesman WHERE salesman_id=?";
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, idField.getText());
            
            pstmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "业务员删除成功！");
            clearFields();
            refreshTable();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "删除业务员失败: " + e.getMessage());
        }
    }

    private void searchSalesman() {
        try {
            StringBuilder sql = new StringBuilder("SELECT * FROM salesman WHERE 1=1");
            
            // 构建查询条件
            if (!idField.getText().trim().isEmpty()) {
                sql.append(" AND salesman_id LIKE ?");
            }
            if (!nameField.getText().trim().isEmpty()) {
                sql.append(" AND name LIKE ?");
            }
            if (!phoneField.getText().trim().isEmpty()) {
                sql.append(" AND phone LIKE ?");
            }

            PreparedStatement pstmt = connection.prepareStatement(sql.toString());
            int paramIndex = 1;

            // 设置查询参数
            if (!idField.getText().trim().isEmpty()) {
                pstmt.setString(paramIndex++, "%" + idField.getText().trim() + "%");
            }
            if (!nameField.getText().trim().isEmpty()) {
                pstmt.setString(paramIndex++, "%" + nameField.getText().trim() + "%");
            }
            if (!phoneField.getText().trim().isEmpty()) {
                pstmt.setString(paramIndex++, "%" + phoneField.getText().trim() + "%");
            }

            // 清空表格
            DefaultTableModel model = (DefaultTableModel) salesmanTable.getModel();
            model.setRowCount(0);

            // 执行查询并显示结果
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                model.addRow(new Object[]{
                    rs.getString("salesman_id"),
                    rs.getString("name"),
                    rs.getString("phone")
                });
            }

            if (model.getRowCount() == 0) {
                JOptionPane.showMessageDialog(this, "未找到匹配的记录！");
            }

        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "查询失败: " + e.getMessage());
        }
    }

    private void clearFields() {
        idField.setText("");
        nameField.setText("");
        phoneField.setText("");
    }
} 